<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
        找出所有和为0的元组。这里为什么left<right?不能left<=right
        因为如果left==right的情况下，依然进入了for循环 left right都等于2 [-4,2,2]
        但是必须三个元素，所以不符合条件
        */
      var threeSum = function (nums) {
        nums.sort((a, b) => a - b);
        let result = [];
        for (let i = 0; i < nums.length; i++) {
          let left = i + 1;
          let right = nums.length - 1;
          if (nums[i - 1] == nums[i]) {
            continue;
          }
          while (left < right) {
            let sum = nums[i] + nums[left] + nums[right];
            if (sum < 0) {
              left++;
            } else if (sum > 0) {
              right--;
            } else {
              while (nums[left] == nums[left + 1]) {
                left++;
              }
              while (nums[right] == nums[right - 1]) {
                right--;
              }
              result.push([nums[i], nums[left], nums[right]]);
              left++;
              right--;
            }
          }
        }
        return result;
      };
      threeSum([-1, 0, 1, 2, -1, -4]);
    </script>
  </body>
</html>
